<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <div class='table-page-search-wrapper'>
      <a-form layout='inline' @keyup.enter.native='search'>
        <a-row :gutter='24'>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-form-item label='确认单号'>
              <a-input placeholder='请输入确认单号' v-model='queryParams.no'></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-form-item label='预出库单号'>
              <a-input placeholder='预出库单号' v-model='queryParams.outorderPreNo'></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <a-form-item label='销售确认人'>
              <a-input placeholder='请输入销售确认人' v-model='queryParams.sealSureUser'></a-input>
            </a-form-item>
          </a-col>

          <template v-if='toggleSearchStatus'>
            <a-col :xl='5' :lg='7' :md='8' :sm='24'>
              <a-form-item label='财务是否确认'>
                <a-select v-model='queryParams.isSure' placeholder='请选择状态'>
                  <a-select-option v-for='(d,i) in stateList' :key='d.id' :value='d.id'>{{ d.value }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>

            <a-col :xl='7' :lg='7' :md='8' :sm='24'>
              <a-form-item label='销售确认日期'>
                <a-range-picker :style="{width: '100%'}" format='YYYY-MM-DD'
                                :placeholder="['开始时间', '结束时间']"
                                v-model='rangePikerDate'
                                @change='onQueryDateChange' />
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl='6' :lg='7' :md='8' :sm='24'>
            <span style='float: left;overflow: hidden;' class='table-page-search-submitButtons'>
              <a-button type='primary' @click='search' icon='search'>查询</a-button>
              <a-button type='primary' @click='resetSearch' icon='reload' style='margin-left: 8px'>重置</a-button>
              <a @click='handleToggleSearch' style='margin-left: 8px'>
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class='table-operator'>
<!--      <a-button @click='addModalShow' type='primary' icon='plus'>新增</a-button>-->
      <a-button type='primary' icon='download' @click="handleExportXls('销售确认单主表')">导出Excel</a-button>

    </div>

    <!-- table区域-begin -->
    <div>
      <div class='ant-alert ant-alert-info' style='margin-bottom: 16px;'>
        <i class='anticon anticon-info-circle ant-alert-icon'></i> 已选择 <a
        style='font-weight: 600'>{{ selectedRowKeys.length }}</a>项
        <a style='margin-left: 24px' @click='onClearSelected'>清空</a>
      </div>

      <a-table
        ref='table'
        size='middle'
        bordered
        rowKey='id'
        class='j-table-force-nowrap'
        :columns='columns'
        :dataSource='flowerPreDataSource'
        :pagination='mainPagination'
        :loading='loading'
        :scroll='{ x: true }'
        :rowSelection='{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}'
        @change='mainPaginationChange'>

        <template slot='htmlSlot' slot-scope='text'>
          <div v-html='text'></div>
        </template>
        <template slot='imgSlot' slot-scope='text'>
          <span v-if='!text' style='font-size: 12px;font-style: italic;'>无图片</span>
          <img v-else :src='getImgView(text)' height='25px' alt=''
               style='max-width:80px;font-size: 12px;font-style: italic;' />
        </template>
        <template slot='fileSlot' slot-scope='text'>
          <span v-if='!text' style='font-size: 12px;font-style: italic;'>无文件</span>
          <a-button
            v-else
            :ghost='true'
            type='primary'
            icon='download'
            size='small'
            @click='uploadFile(text)'>
            下载
          </a-button>
        </template>
        <span slot='state' slot-scope='text, record'>
          <a-tag class='rcicon-tag' v-if='record.state==0'>草稿</a-tag>
          <a-tag class='ant-tag-blue' v-else-if='record.state==1'>基地负责人审批</a-tag>
          <a-tag class='ant-tag-blue' v-else-if='record.state==2'>运管备案</a-tag>
          <a-tag class='ant-tag-green' v-else-if='record.state==3'>财务确认</a-tag>
          <a-tag class='ant-tag-red' v-else-if='record.state==-2'>已删除</a-tag>
        </span>
        <span slot='action' slot-scope='text, record'>
<!--          v-has='"Pre:sealSure"'-->
<!--           v-has='"Pre:sealSureBack"' -->
          <a-button  v-if='record.state==1' type="primary" @click="editModalShow(record)">运管备案</a-button>
          <a-button v-else-if='record.state==2'  type="danger" @click="editModalShow(record)">撤销运管备案</a-button>
          <a v-else @click='editModalShow(record)'>详情</a>
          <a-divider type='vertical' />

        </span>

      </a-table>
    </div>

    <template>

      <!--    <flowerPre-modal ref="modalForm" @ok="modalFormOk"></flowerPre-modal>-->
      <a-modal v-model:visible='addOrEditVisible' width='85%' :title='firstModalTitle' layout='inline'
               :maskClosable='false'>
        <a-spin :spinning='firstModalSpinning' tip='数据保存中...'>
          <template>
            <a-form-model ref='form' layout='inline' :model='flowerPre' :rules='validatorRules'>
              <a-row>
                <a-col :xl='8' :lg='8' :md='12' :sm='24'>
                  <a-form-model-item label='确认单号'>
                    <a-input disabled v-model='flowerPre.no' placeholder='自动生成' style='width: 100%' />
                  </a-form-model-item>
                </a-col>
                <a-col :lg='8' :md='12' :sm='24'>
                  <a-form-model-item label='预出库单' required prop='outorderPreNo'>
                    <a-button-group>
                      <a-input v-model='flowerPre.outorderPreNo' disabled />
                      <a-button :disabled='flowerPre.state!=0' type='primary' icon='search' @click='preorderModalShow'>选择</a-button>
                    </a-button-group>
                  </a-form-model-item>
                </a-col>
                <a-col :xl='8' :lg='8' :md='12' :sm='24'>
                  <div style='display: inline-block;color: red;'>*</div>
                  <div style='display: inline-block'>客户：</div>
                  <div style='display: inline-block;width: 80%'>
                    <a-input v-model='flowerPre.user' disabled />
                  </div>
                </a-col>
                <a-col :xl='8' :lg='8' :md='12' :sm='24' >
                  <a-form-model-item label='账期' prop='period'>
                    <a-radio-group v-model='flowerPre.period' @change='periodChange'  :disabled='flowerPre.state!=0' >
                      <a-radio v-for='(item,index) in periodList' :key='index' :value='item'>{{ item }}</a-radio>
                    </a-radio-group>
                  </a-form-model-item>
                </a-col>
                <a-col :lg='8' :md='12' :sm='24' >
                  <a-form-model-item label='是否开票' required prop='isinvoice'>
                    <a-radio-group    :disabled='flowerPre.state!=0'
                                      v-model='flowerPre.isinvoice' @change='isinvoiceChange'>
                      <a-radio value='是'>是</a-radio>
                      <a-radio value='否'>否</a-radio>
                    </a-radio-group>
                  </a-form-model-item>
                </a-col>
                <a-col :xl='8' :lg='8' :md='12' :sm='24'>
                  <a-form-model-item label='渠道' required prop='channel'>
                    <a-select v-model='flowerPre.channel' placeholder='请选择渠道' style='width: 130px;' disabled
                              @change='channelChange'>
                      <a-select-option v-for='(d,i) in channelList' :key='d.id' :value='d.channel'>{{ d.channel }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>
                </a-col>
                <a-col :xl='8' :lg='8' :md='12' :sm='24' v-show='accountnoShow'>
                  <a-form-model-item label='账号' required prop='accountno'>
                    <a-select v-model='flowerPre.accountno' placeholder='请选择账号' style='width: 130px;' disabled>
                      <a-select-option v-for='(d,i) in accountnoList' :key='d.id' :value='d.account'>{{ d.account }}
                      </a-select-option>
                    </a-select>
                  </a-form-model-item>

                </a-col>

                <a-col :lg='8' :md='12' :sm='24'>
                  <a-form-model-item label='地址' required prop='address'>
                    <a-input  :disabled='flowerPre.state!=0'
                              v-model='flowerPre.address' placeholder='请输入地址' />
                  </a-form-model-item>
                </a-col>

                <a-col :xl='8' :lg='8' :md='12' :sm='24'>
                  <a-form-model-item label='出库人'>
                    <a-input disabled v-model='flowerPre.stockOutUser' placeholder='自动生成' style='width: 100%' />
                  </a-form-model-item>
                </a-col>

                <!--                <a-col :lg='8' :md='12' :sm='24'>
                                  <a-form-model-item label='客户' required prop='user'>
                                    <a-button-group>
                                      <a-input v-model='flowerPre.user' disabled />
                                      <a-button type='primary' icon='search' @click='customModalShow'>选择</a-button>
                                    </a-button-group>
                                  </a-form-model-item>
                                </a-col>-->


                <a-col :xl='8' :lg='8' :md='12' :sm='24'>
                  <a-form-model-item label='数量'>
                    <a-input-number disabled v-model='flowerPre.number' placeholder='保存后自动计算' style='width: 100%' />
                  </a-form-model-item>
                </a-col>

                <a-col :xl='8' :lg='8' :md='12' :sm='24'>
                  <a-form-model-item label='总价'>
                    <a-input-number disabled v-model='flowerPre.toalprice' placeholder='保存后自动计算' style='width: 100%' />
                  </a-form-model-item>
                </a-col>
              </a-row>
            </a-form-model>
          </template>

          <a-divider />
          <div style='margin-top: -20px'>

            <div>
              <div style='font-size: 20px;color: #0742f3;margin-bottom: 3px;display: inline-block'>销售商品</div>
              <div style='display: inline-block;margin-left: 20px;'>
                <a-button v-if='flowerPre.state==0' type='primary' icon='plus'
                          @click='varietyModalShow'>新增
                </a-button>
              </div>
              <div style='display: inline-block;margin-left: 100px;font-size: 18px'>
                <span>总价合计：</span><span style='color: red'>{{ allTotalPrice }}</span>
              </div>
            </div>
            <div style='margin-top: 7px'>
              <a-table :columns='varietyColumns' :data-source='varietyDataSource'
                       bordered
                       row-key='id'
                       :loading='varietyLoading'
                       :pagination='false'
                       :scroll='{ x: true, y: 300 }'>

                <template v-for="colNumber in ['number']" :slot='colNumber' slot-scope='text, record, index'>
                  <div :key='colNumber' style='float: left;margin-right: 0'>
                    <a-input v-model:value='record.number' placeholder='请输入销售数量'
                             :disabled='flowerPre.state!=0'
                             @change='autugetprice(record,record.number,record.totalprice)' />
                  </div>
                </template>


                <template v-for="colPrice in ['price']" :slot='colPrice' slot-scope='text, record, index'>
                  <div :key='colPrice' style='float: left;margin-right: 0'>
                    <a-input disabled v-model:value='record.price' placeholder='请输入销售单价' />
                  </div>
                </template>

                <template v-for="colPrice2 in ['totalprice']" :slot='colPrice2' slot-scope='text, record, index'>
                  <div :key='colPrice2' style='float: left;margin-right: 0'>
                    <a-input v-model:value='record.totalprice' placeholder='请输入总价'
                             :disabled='flowerPre.state!=0'
                             @change='autugetprice(record,record.number,record.totalprice)' />
                  </div>
                </template>

                <template v-if='flowerPre.state==0'  slot='operation' slot-scope='text, record'>
                  <a-popconfirm v-if='varietyDataSource.length' title='确定删除?'
                                @confirm='() => varietyDelete(record.id)'>
                    <a>删除</a>
                  </a-popconfirm>
                </template>
              </a-table>
            </div>
          </div>

          <a-divider />
          <div style='margin-top: -20px'>

            <div>
              <div style='font-size: 20px;color: #0742f3;margin-bottom: 3px;display: inline-block'>货损商品</div>
              <div style='display: inline-block;margin-left: 20px;'>
                <a-button v-if='flowerPre.state==0' type='primary' icon='plus'
                          @click='varietyModalShow2'>选择
                </a-button>
              </div>
              <div style='display: inline-block;margin-left: 100px;font-size: 18px'>
                <span>总价合计：</span><span style='color: red'>{{ allTotalPrice2 }}</span>
              </div>
            </div>
            <div style='margin-top: 7px'>
              <a-table :columns='varietyColumns' :data-source='varietyDataSource2'
                       bordered
                       row-key='id'
                       :loading='varietyLoading'
                       :pagination='false'
                       :scroll='{ x: true, y: 300 }'>

                <template v-for="colNumber in ['number']" :slot='colNumber' slot-scope='text, record, index'>
                  <div :key='colNumber' style='float: left;margin-right: 0'>
                    <a-input v-model:value='record.number' placeholder='请输入销售数量'
                             :disabled='flowerPre.state!=0'
                             @change='autugetprice(record,record.number,record.totalprice)' />
                  </div>
                </template>


                <template v-for="colPrice in ['price']" :slot='colPrice' slot-scope='text, record, index'>
                  <div :key='colPrice' style='float: left;margin-right: 0'>
                    <a-input disabled v-model:value='record.price' placeholder='请输入销售单价' />
                  </div>
                </template>

                <template v-for="colPrice2 in ['totalprice']" :slot='colPrice2' slot-scope='text, record, index'>
                  <div :key='colPrice2' style='float: left;margin-right: 0'>
                    <a-input v-model:value='record.totalprice' placeholder='请输入总价'
                             :disabled='flowerPre.state!=0'
                             @change='autugetprice(record,record.number,record.totalprice)' />
                  </div>
                </template>

                <template v-if='flowerPre.state==0' slot='operation' slot-scope='text, record'>
                  <a-popconfirm v-if='varietyDataSource.length' title='确定删除?'
                                @confirm='() => varietyDelete2(record.id)'>
                    <a>删除</a>
                  </a-popconfirm>
                </template>
              </a-table>
            </div>
          </div>
        </a-spin>
        <template slot='footer'>
          <a-button key='back' :loading='firstModalSaveLoading' @click='addOrEditVisible=false'>
            关闭
          </a-button>
<!--
          <a-button  v-if='flowerPre.state==0' key='submit' type='primary' :loading='firstModalSaveLoading' @click='flowerPreAddOrEdit'>
            保存
          </a-button>
-->
          <a-button  v-if='flowerPre.state==1' :loading='firstModalSaveLoading' type="primary" @click="sealSure(flowerPre)">运管备案</a-button>
          <a-button v-else-if='flowerPre.state==2' :loading='firstModalSaveLoading'  type="danger" @click="sealSureBack(flowerPre)">撤销运管备案</a-button>

        </template>
      </a-modal>


      <a-modal v-model:visible='varietyVisible' width='75%' title='销售商品选择' @ok='varietyAdd'>
        <!--        selectVarietyDataSource 改为了  preOrderInfoList缓存数据  gf  2022年12月9日15:42:59-->
        <a-table :columns='selectVarietyColumns' :data-source='preOrderInfoList' bordered
                 :loading='selectVarietyLoading'
                 :row-selection="{selectedRowKeys: selectedRowKeys,type: 'checkbox',onChange:onVarietySelectChange,onSelect:varietyOnSelect,
               onSelectAll:varietyOnSelectAll}"
                 row-key='id'
                 :scroll='{y:280}'
                 :pagination='varietyPagination'
                 @change='varietyPaginationChange'
        ></a-table>
      </a-modal>
      <a-modal v-model:visible='varietyVisible2' width='75%' title='货损商品选择' @ok='varietyAdd2'>
        <a-table :columns='selectVarietyColumns' :data-source='preOrderInfoList' bordered
                 :loading='selectVarietyLoading'
                 :row-selection="{selectedRowKeys: selectedRowKeys2,type: 'checkbox',onChange:onVarietySelectChange2,onSelect:varietyOnSelect2,
               onSelectAll:varietyOnSelectAll2}"
                 row-key='id'
                 :scroll='{y:280}'
                 :pagination='varietyPagination2'
                 @change='varietyPaginationChange2'
        ></a-table>
      </a-modal>

      <!--    选择客户的弹窗-->
      <a-modal v-model:visible='customVisible' width='70%' title='客户选择' @ok='customAdd'>
        <div style='margin-bottom: 10px'>
          <a-row style='margin-top: 10px'>
            <a-col :span='10'>
              <div style='display: inline-block;width: 90px;'>客户名称：</div>
              <div style='display: inline-block;width: 70%'>
                <a-input v-model='queryCustomParams.name' placeholder='请输入客户名称' allow-clear
                         @change='searchCustom' />
              </div>
            </a-col>
            <a-col :span='10'>
              <div style='display: inline-block;width: 90px;'>客户电话：</div>
              <div style='display: inline-block;width: 70%'>
                <a-input v-model='queryCustomParams.phone' placeholder='请输入客户电话' allow-clear
                         @change='searchCustom' />
              </div>
            </a-col>
            <a-col :span='4'>
              <a-button type='primary' icon='search' @click='searchCustom'>
                查询
              </a-button>
            </a-col>
          </a-row>
        </div>
        <a-table :columns='customColumns' :data-source='customDataSource' bordered
                 :loading='customLoading'
                 :row-selection="{selectedRowKeys: selectedRowKeys,type: 'radio',onChange:customOnChange}"
                 row-key='id'
                 :scroll='{y:280}'
                 :pagination='customPagination'
                 @change='selectCustomPaginationChange'
        ></a-table>
      </a-modal>


      <!--    选择预出库的弹窗-->
      <!--    选择预出库的弹窗-->
      <a-modal v-model:visible='preorderVisible33' width='75%' title='预出库单选择' @ok='PreOrderAdd'>
        <div style='margin-bottom: 10px'>
          <a-row style='margin-top: 10px'>
            <a-col :span='16'>
              <div style='display: inline-block;width: 90px;'>预出库单号：</div>
              <div style='display: inline-block;width: 70%'>
                <a-input v-model='querypreorderParams.orderNo' placeholder='单号' allow-clear
                         @change='searchPreOrder' />
              </div>
            </a-col>

            <a-col :span='4'>
              <a-button type='primary' icon='search' @click='searchPreOrder'>
                查询
              </a-button>
            </a-col>
          </a-row>
        </div>
        <a-table :columns='preorderColumns' :data-source='preorderDataSource' bordered
                 :loading='customLoading'
                 :row-selection="{selectedRowKeys: selectedRowKeys,type: 'radio',onChange:preorderOnChange}"
                 row-key='orderNo'
                 :scroll='{y:580}'
                 :pagination='preorderPagination'
                 @change='selectPreOrderPaginationChange'
        ></a-table>
      </a-modal>
    </template>


  </a-card>
</template>

<script>

import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import FlowerPreModal from './modules/FlowerPreModal'
import '@/assets/less/TableExpand.less'
import { ifInteger, ifNumber, ifNumber1 } from '../../utils/ifNumber'
import {
  getFlowerPreVarietys3, getFlowerPre, getFlowerPreinfoByMainId, getFlowerPreinfoByMainId2, flowerPreAdd, flowerPreEdit,
  flowerPreDelete, flowerPreDeleteBatch, getFlowerChannel, getFlowerAccountByMainId,
  period, getFlowerCustom, getFlowerPreOutorder, getPreOrderInfolistByNo,sealSureOut ,sealSureOutBack,  pipSureOut,
  pipSureOutBack,
} from '../../api/vegetableAPI'
import { getUuid } from '../../utils/uuid'
import moment from 'moment'
import { downFile } from '@/api/manage'
import { getTodayDate, getCurrentYearAndMonth } from '@/utils/getDate'
import store from '@/store'

export default {
  name: 'FlowerPreList',
  mixins: [JeecgListMixin],
  components: {
    FlowerPreModal
  },
  data() {
    return {
      queryParams: {// 主页查询
        no: '',//确认单号
        sealSureUser: '',//销售确认人
        isSure: '',//是否财务确认
        sDate: '',//开始时间
        eDate: ''//结束时间
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      preorderVisible33: false,
      rangePikerDate: [],
      // sourceBaseList: [],//基地列表
      // sourceGreenhouseList: [],//地块列表
      queryVarietyParams: {// 商品选择弹窗的查询
        variety: '',
        varietyCode: ''
      },
      //选择财务是否确认的list
      stateList: [{ id: '', value: '全部' }, { id: 1, value: '是' }, { id: 2, value: '否' }],
      description: '销售确认单主表管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'state',
          scopedSlots: { customRender: 'state' },
          width: 70
        },
        {
          title: '确认单号',
          align: 'center',
          dataIndex: 'no',
          width: 140
        }, {
          title: '预出库单号',
          align: 'center',
          dataIndex: 'outorderPreNo',
          width: 100
        }, {
          title: '账期',
          align: 'center',
          width: 100,
          dataIndex: 'period'
        },/*{
          title: '冷库',
          dataIndex: 'storehouse_dictText',
          width: 100,
        },*/
        {
          title: '数量',
          align: 'center',
          dataIndex: 'number'
        },
        {
          title: '总价',
          align: 'center',
          dataIndex: 'toalprice',
          width: 100
        },   {
          title: '货损数量',
          align: 'center',
          dataIndex: 'numberhs'
        },
        {
          title: '货损金额',
          align: 'center',
          dataIndex: 'toalpricehs',
          width: 100
        }, {
          title: '基地负责人',
          align: 'center',
          dataIndex: 'sealSureUser',
          width: 100
        },
        {
          title: '基地负责人确认时间',
          align: 'center',
          dataIndex: 'sealSureTime',
          width: 100
        }, {
          title: '运管备案',
          align: 'center',
          dataIndex: 'pipSure',
          width: 100
        },
        {
          title: '运管备案时间',
          align: 'center',
          dataIndex: 'pipSureTime',
          width: 100
        },

        {
          title: '财务确认人',
          align: 'center',
          dataIndex: 'finaSureUser',
          width: 100
        },
        {
          title: '财务确认日期',
          align: 'center',
          dataIndex: 'finaSureTime',
          width: 100
        },

        {
          title: '渠道',
          align: 'center',
          dataIndex: 'channel',
          ellipsis: true,
          width: 80
        }, {
          title: '账号',
          align: 'center',
          dataIndex: 'accountno',
          ellipsis: true,
          width: 100
        }, {
          title: '是否开票',
          align: 'center',
          dataIndex: 'isinvoice',
          width: 90
        },
        {
          title: '创建日期',
          align: 'center',
          dataIndex: 'createTime',
          customRender: function(text) {
            return !text ? '' : (text.length > 10 ? text.substr(0, 10) : text)
          },
          width: 100
        },

        {
          title: '创建人',
          align: 'center',
          dataIndex: 'createUser_dictText',
          width: 100
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 150,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/flower/flowerPre/list',
        delete: '/flower/flowerPre/delete',
        deleteBatch: '/flower/flowerPre/deleteBatch',
        exportXlsUrl: '/flower/flowerPre/exportXls',
        importExcelUrl: 'flower/flowerPre/importExcel'
      },
      dictOptions: {},
      flowerPreDataSource: [],
      firstModalTitle: '',
      firstModalSpinning: false,//第一个弹窗是否处于加载中
      addOrEditFlag: 'add',//打开的弹窗是新增还是编辑的标识
      varietyLoading: false,//是否显示第一个弹窗中表格的加载状态
      selectVarietyLoading: false,//是否显示第二个弹窗中表格的加载状态
      addOrEditVisible: false,//是否打开新增或编辑的弹窗
      varietyVisible: false,//是否打开商品选择的弹窗
      varietyVisible2: false,//是否打开商品选择的弹窗
      flowerPre: {
        // sourceBase: '',//基地
        // sourceGreenhouse: '',//地块
        period: '',//账期
        number: '',//数量
        toalprice: '',//总价
        userid: '',//客户id
        user: '',//
        address: '',//
        stockOutTime: '',//出库日期
        sealSureTime: '',//销售确认日期
        sealSureUser: '',//销售确认人
        storehouse: '',//冷库
        finaSureTime: '',//财务确认日期
        finaSureUser: '',//财务确认人
        isinvoice: '',//是否开票
        channel: '',//渠道
        accountno: ''//账号
      },
      channelList: [],
      accountnoList: [],
      accountnoShow: false,//第一个弹窗中是否显示账号的选择框
      defaultStockOutTime: '',
      defaultSealSureTime: '',
      dateFormat: 'YYYY-MM-DD',
      varietyColumns: [// 第一个弹窗的表头
        {
          title: '基地',
          align: 'center',
          dataIndex: 'sourceBase_dictText',
          width: 120
        }, {
          title: '地块',
          align: 'center',
          dataIndex: 'sourceGreenhouse_dictText',
          width: 100
        }, {
          title: '冷库',
          dataIndex: 'storehouse_dictText',
          align: 'center',
          width: 100
        },
        {
          title: '批次',
          align: 'center',
          dataIndex: 'productionId'
          // width: 120,
        }, {
          title: '产品',
          dataIndex: 'variety',
          align: 'center',
          width: 100
        }, {
          title: '产品编码',
          dataIndex: 'varietyCode',
          align: 'center',
          width: 120
        }, {
          title: '规格',
          dataIndex: 'packingSpecifications',
          align: 'center',
          width: 100
        }, {
          title: '单位',
          dataIndex: 'flowerPoleLength',
          align: 'center',
          width: 65
        }, {
          title: '等级',
          dataIndex: 'classes',
          width: 65
        }, {
          title: '销售数量',
          dataIndex: 'number',
          align: 'center',
          scopedSlots: { customRender: 'number' },
          width: 120
        }, {
          title: '单价',
          dataIndex: 'price',
          align: 'center',
          scopedSlots: { customRender: 'price' },
          width: 120
        }, {
          title: '总价',
          dataIndex: 'totalprice',
          align: 'center',
          scopedSlots: { customRender: 'totalprice' },
          width: 140
        },
        {
          title: '操作',
          dataIndex: 'operation',
          align: 'center',
          width: 70,
          fixed: 'right',
          scopedSlots: { customRender: 'operation' }
        }
      ],
      hoseList: [], //冷库列表
      selectVarietyColumns: [// 第二个弹窗的表头
        {
          title: '基地',
          align: 'center',
          dataIndex: 'sourceBase_dictText',
          width: 120
        }, {
          title: '大棚',
          align: 'center',
          dataIndex: 'sourceGreenhouse_dictText',
          width: 100
        },  {
          title: '冷库',
          dataIndex: 'storehouse_dictText',
          align: 'center'
        }, {
          title: '产品',
          dataIndex: 'variety',
          align: 'center'
        }, {
          title: '产品编码',
          dataIndex: 'varietyCode',
          align: 'center'
        }, {
          title: '规格',
          dataIndex: 'packingSpecifications',
          align: 'center'
        }, {
          title: '单位',
          dataIndex: 'flowerPoleLength',
          align: 'center'
        }, {
          title: '等级',
          dataIndex: 'classes',
          width: 65
        }, {
          title: '数量',
          dataIndex: 'number',
          align: 'center'
        }, {
          title: '单价',
          dataIndex: 'price',
          align: 'center'
        }, {
          title: '总金额',
          dataIndex: 'totalprice',
          align: 'center'
        }
      ],
      varietyNumber: 1,
      varietyDataSource: [],// 第一个弹窗中的商品列表
      varietyDataSource2: [],// 第一个弹窗中的商品列表
      preOrderInfoList: [],// 预出库单子表数据---缓存，用于选择货损等。
      validatorRules: {
        /*  stockOutTime: [
            { required: true, message: '请输入出库时间!' }
          ],*/
        outorderPreNo: [
          { required: true, message: '请选择预出库单!' }
        ],
        period: [
          { required: true, message: '请输入账期!' },
          { validator: this.validateRoleCode }
        ],
        channel: [
          { required: true, message: '请输入渠道!' }
        ],
        accountno: [
          { required: true, message: '请输入账号!' }
        ],
        isinvoice: [
          { required: true, message: '请输入是否开票!' }
        ],
        address: [
          { required: true, message: '请输入地址!' }
        ]
      },
      selectVarietyDataSource: [],// 第二个弹窗中可选择的商品列表
      selectVariety: [],// 第二个弹窗中已选择的商品
      selectVariety2: [],// 第二个弹窗中已选择的商品
      mainPagination: {// 主页表格的分页
        total: 0,
        current: 1,
        pageSize: 10,//每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],//每页中显示的数据
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      },
      varietyPagination: {// 商品选择弹窗中表格的分页
        total: 0,
        current: 1,
        pageSize: 10,//每页中显示10条数据
        showSizeChanger: false,
        showQuickJumper: true,
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      },
      varietyPagination2: {// 商品选择弹窗中表格的分页
        total: 0,
        current: 1,
        pageSize: 10,//每页中显示10条数据
        showSizeChanger: false,
        showQuickJumper: true,
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      },
      allTotalPrice: 0,//编辑弹窗中所有商品的总价
      allTotalPrice2: 0,//编辑弹窗中所有商品的总价
      firstModalSaveLoading: false,//第一个弹窗保存按钮是否处于加载中
      periodList: [],//从后台取回的账期列表

      customVisible: false,//是否打开客户选择的弹窗
      customColumns: [// 客户选择弹窗中表格的表头
        {
          title: '客户编码',
          dataIndex: 'code',
          align: 'center',
          width: 120
        }, {
          title: '客户名称',
          dataIndex: 'name',
          align: 'center',
          width: 150
        }, {
          title: '客户电话',
          dataIndex: 'phone',
          align: 'center',
          width: 120
        }, {
          title: '客户地址',
          dataIndex: 'address',
          align: 'center'
        }
      ],
      preorderColumns: [// 客户选择弹窗中表格的表头
        {
          title: '预出库单号',
          dataIndex: 'orderNo',
          align: 'center'
        }, {
          title: '渠道',
          dataIndex: 'channel',
          align: 'center'
        }, {
          title: '出库人',
          dataIndex: 'createUser',
          align: 'center'
        }, {
          title: '地址',
          dataIndex: 'address',
          align: 'center'
        }
      ],
      customDataSource: [],//客户列表
      preorderDataSource: [],//预出库单列表
      selectCustom: {},//客户选择弹窗中已选择的客户
      selectpreOrder: {},// 选择弹窗中已选择的与出库单
      customPagination: {// 客户表格的分页
        total: 0,
        current: 1,
        pageSize: 10,//每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],//每页中显示的数据
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      },
      preorderPagination: {// 客户表格的分页
        total: 0,
        current: 1,
        pageSize: 10,//每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],//每页中显示的数据
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      },
      customLoading: false,
      queryCustomParams: {// 客户选择弹窗的查询
        name: '',
        phone: ''
      },
      querypreorderParams: {// 客户选择弹窗的查询
        orderNo: '',
        createUser: '',
        state: 0
      },
      selectedRowKeys2:[],
      selectionRows2:[],
      pressesUrl:{
        getForm:'/actBusiness/getForm',
        addApply:'/actBusiness/add',
        editForm:'/actBusiness/editForm',
      }
    }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  created() {
    //获取冷库列表
    this.hoseList = JSON.parse(localStorage.getItem('ch_storehouse') ? localStorage.getItem('ch_storehouse') : '')
    this.getChannel()
    this.getPeriod()
  },
  mounted() {
    this.queryFlowerPre()
    //this.queryFlowerBase()
  },
  methods: {
    moment,
    search() {// 主页中根据条件查询
      this.mainPagination.current = 1
      this.queryFlowerPre()
    },
    onQueryDateChange(date, dateString) {// 日期段选择改变时的回调
      this.queryParams.sDate = dateString[0]
      this.queryParams.eDate = dateString[1]
    },
    resetSearch() {// 重置查询
      this.queryParams = {// 主页查询
        no: '',//确认单号
        sealSureUser: '',//销售确认人
        isSure: '',//是否财务确认
        sDate: '',//开始时间
        eDate: ''//结束时间
      },
        this.rangePikerDate = []
      this.search()
    },
    searchFlowerVarietys() {//根据条件查询商品选择弹窗中的商品列表
      this.varietyPagination.current = 1
      this.queryFlowerVarietys()
    },
    mainPaginationChange(pagination) {
      this.mainPagination.current = pagination.current
      this.mainPagination.pageSize = pagination.pageSize
      this.queryFlowerPre()
    },
    varietyPaginationChange(pagination) {
      this.varietyPagination = pagination
      this.queryFlowerVarietys()
    },
    varietyPaginationChange2(pagination) {
      this.varietyPagination = pagination
      this.queryFlowerVarietys()
    },
    queryFlowerPre() {// 获取销售单
      this.loading = true
      this.flowerPreDataSource.length = 0
      let params = {
        pageNo: this.mainPagination.current,
        pageSize: this.mainPagination.pageSize
      }
      params = { ...this.queryParams, ...params }
      getFlowerPre(params).then(res => {
        if (res.success) {
          this.mainPagination.total = res.result.total
          this.flowerPreDataSource = res.result.records
        } else {
          this.$message.error(res.message)
        }
        this.loading = false
      })
    },
    addModalShow() {//打开第一个弹窗(新增)
      this.addOrEditFlag = 'add'
      this.firstModalTitle = '新增'
      let realname = store.getters.userInfo.realname
      let phone = store.getters.userInfo.phone
      let userName = store.getters.userInfo.username
      this.flowerPre = {
        period: this.periodList.length === 1 ? this.periodList[0] : this.periodList[1],//账期
        number: '',//数量
        toalprice: '',//总价
        userid: '',//
        user: '',//
        address: '',//
        stockOutUser: realname,//
        stockOutTime: '',//出库日期
        sealSureTime: '',//销售确认日期
        sealSureUser: '',//销售确认人
        storehouse: '',//冷库
        finaSureTime: '',//财务确认日期
        finaSureUser: '',//财务确认人
        isinvoice: '',//是否开票
        channel: '',//渠道
        accountno: '',//账号
        state: 0 ,
      }
      // this.todayDate()

      // this.varietyDataSource = []
      this.allTotalPrice = 0
      this.getPeriod()
      this.firstModalSaveLoading = false
      this.addOrEditVisible = !this.addOrEditVisible
    },
    editModalShow(record) {//打开第一个弹窗(编辑)
      this.addOrEditFlag = 'edit'
      this.firstModalTitle = '编辑'
      this.flowerPre = record
      if (this.flowerPre.accountno !== '') {//打开编辑界面时如果账号有数据的话，要把账号显示出来
        this.accountnoShow = true
      }
      this.varietyDataSource.length = 0
      this.allTotalPrice = 0
      this.queryFlowerPreinfo(record.id)
      this.setPeriod()
      this.firstModalSaveLoading = false
      this.addOrEditVisible = !this.addOrEditVisible
      if (this.flowerPre.outorderPreNo) {
        this.queryPreOrderInfolistByNo(this.flowerPre.outorderPreNo, true)
      }
    },
    varietyModalShow() {//打开/关闭第二个弹窗
      // 销售
      if (!this.flowerPre.outorderPreNo) {
        this.$message.error('请先选择【预出库单号】')
        return
      }
      /*   if (this.flowerPre.channel === '') {
           this.$message.error('请先选择渠道')
           return
         }
         if (this.accountnoShow && this.flowerPre.accountno === '') {
           this.$message.error('请先选择账号')
           return
         }*/

      /*设置下面这两行是为了处理再次打开商品选择弹窗时，
      还会在界面上保留上次选择商品而实际上没有选择任何商品的问题*/
      this.selectedRowKeys.length = 0
      this.selectionRows.length = 0

      this.selectVariety = []
      this.varietyPagination = {// 商品选择弹窗中表格的分页
        total: this.preOrderInfoList.length,
        current: 1,
        pageSize: 50,//每页中显示10条数据
        showSizeChanger: false,
        showQuickJumper: true,
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      }

      this.queryVarietyParams = {// 商品选择弹窗的查询
      }
      // this.queryFlowerVarietys()  //改为缓存获取
      this.varietyVisible = !this.varietyVisible
    },
    varietyModalShow2() {//打开/关闭第二个弹窗---货损
      // 销售
      if (!this.flowerPre.outorderPreNo) {
        this.$message.error('请先选择【预出库单号】')
        return
      }
      /*设置下面这两行是为了处理再次打开商品选择弹窗时，
      还会在界面上保留上次选择商品而实际上没有选择任何商品的问题*/
      this.selectedRowKeys2.length = 0
      this.selectionRows2.length = 0

      this.selectVariety2 = []
      this.varietyPagination = {// 商品选择弹窗中表格的分页
        total: this.preOrderInfoList.length,
        current: 1,
        pageSize: 50,//每页中显示10条数据
        showSizeChanger: false,
        showQuickJumper: true,
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      }

      this.queryVarietyParams = {// 商品选择弹窗的查询
      }
      // this.queryFlowerVarietys()  //改为缓存获取
      this.varietyVisible2 = !this.varietyVisible2
    },
    todayDate() {// 设置新增弹窗中的出库时间的默认值为当前日期
      this.defaultStockOutTime = getTodayDate()
      this.flowerPre.stockOutTime = getTodayDate()
    },
    queryFlowerPreinfo(id) {//获取第一个弹窗的商品数据
      this.varietyLoading = true
      let params = {// 因为第一个弹窗中的表格会有新增商品的数据，因此无法使用分页，故将pageSize设大一些
        pageNo: 1,
        pageSize: 1000,
        id: id
      }
      getFlowerPreinfoByMainId(params).then(res => {
        if (res.success) {
          let records = res.result.records
          this.allTotalPrice = 0
          for (let item of records) {
            if (!item.totalprice) {
              item.totalprice = 0
            }
            this.allTotalPrice += item.totalprice * 10 / 10  // 计算总价合计
          }
          this.allTotalPrice = this.allTotalPrice.toFixed(2)
          this.varietyDataSource = records
          this.varietyDataSource.map(item => {// 将uuid封装进varietyDataSource中的各用户对象中,为table中的key使用
            item.uuid = getUuid()
          })
        } else {
          this.$message.error(res.message)
        }
        this.varietyLoading = false
      })
      //货损 货损 货损 货损 货损
      getFlowerPreinfoByMainId2(params).then(res => {
        if (res.success) {
          let records = res.result.records
          this.allTotalPrice2 = 0
          for (let item of records) {
            if (!item.totalprice) {
              item.totalprice = 0
            }
          }
          this.varietyDataSource2 = records
          this.varietyDataSource2.map(item => {// 将uuid封装进varietyDataSource中的各用户对象中,为table中的key使用
            item.uuid = getUuid()
          })
        } else {
          this.$message.error(res.message)
        }
        this.varietyLoading = false
      })
    },
    /* queryFlowerVarietys() {// 获取第二个弹窗中的商品列表
       this.selectVarietyLoading = true
       // let userName = store.getters.userInfo.username
       // let post = store.getters.userInfo.post
       let params = {
         pageNo: this.varietyPagination.current,
         pageSize: this.varietyPagination.pageSize,
         channel: this.flowerPre.channel,
         accountno: this.flowerPre.accountno
         // createUser: userName
       }

       // if(!post  || "businessPerson" == post){
       //   params.createUser = userName
       // }else{
       //   params.createUser = ""
       // }
       params = { ...this.queryVarietyParams, ...params }
       getFlowerPreVarietys3(params).then(res => {
         if (res.success) {
           this.varietyPagination.total = res.result.total
           this.selectVarietyDataSource = res.result.records

           // 将uuid封装进selectVarietyDataSource中的各用户对象中,为table中的key使用
           this.selectVarietyDataSource.map(item => {
             item.uuid = getUuid()
             delete item.id
           })
           // 将varietyNumber封装进selectVarietyDataSource中的各用户对象中,为商品选择弹窗中table的key使用
           if (this.varietyPagination.current > 1) {
             this.varietyNumber = (this.varietyPagination.current - 1) * 10 + 1
           } else {
             this.varietyNumber = 1
           }
           for (let item of this.selectVarietyDataSource) {
             item.varietyNumber = this.varietyNumber
             this.varietyNumber += 1
           }
         } else {
           this.$message.error(res.message)
         }
         this.selectVarietyLoading = false
       })
     },*/
    onVarietySelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys// 如果不加这两行的话无法单选
      this.selectionRows = selectionRows
    },
    varietyOnSelect(record, selected, selectedRows) {//选择/取消选择某个商品的回调
      if (selected) {//如果是选择某个商品的操作，就将所选择的商品添加进selectVariety
        this.selectVariety.push(record)
      } else {//如果是取消选择某个商品的操作，则从selectVariety中删除相应的商品
        this.selectVariety = this.selectVariety.filter(item => item.varietyNumber !== record.varietyNumber)
      }
    },
    varietyOnSelectAll(selected, selectedRows, changeRows) {//选择/取消选择所有商品的回调
      if (selected) {//如果是选择所有商品的操作，就将所选择的商品添加进selectVariety
        this.selectVariety = [...this.selectVariety, ...changeRows]
      } else {//如果是取消选择所有商品的操作，则从selectVariety中删除相应的商品
        for (let i of changeRows) {
          this.selectVariety = this.selectVariety.filter(item => item.varietyNumber !== i.varietyNumber)
        }
      }
    },
    varietyAdd() {// 第二个弹窗中的新增商品
      for (let item of this.selectVariety) {
        item.preinfoid = item.id
        item.createUser = ''
        item.createTime = ''
        item.updateTime = ''
        item.updateUser = ''
        const dataSource = [...this.varietyDataSource]
        let x = dataSource.filter(item2 => item2.id === item.id)
        if (x.length == 0) {
          this.varietyDataSource.push(item)
        }
      }
      this.varietyVisible = !this.varietyVisible
    },
    varietyDelete(id) {// 第一个弹窗中删除商品
      const dataSource = [...this.varietyDataSource]
      this.varietyDataSource = dataSource.filter(item => item.id !== id)

      this.getTotalPrice()
    },
    //货损
    //货损
    //货损
    //货损
    onVarietySelectChange2(selectedRowKeys, selectionRows) {
      this.selectedRowKeys2 = selectedRowKeys// 如果不加这两行的话无法单选
      this.selectionRows2 = selectionRows
    },
    varietyOnSelect2(record, selected, selectedRows) {//选择/取消选择某个商品的回调
      if (selected) {//如果是选择某个商品的操作，就将所选择的商品添加进selectVariety
        this.selectVariety2.push(record)
      } else {//如果是取消选择某个商品的操作，则从selectVariety中删除相应的商品
        this.selectVariety2 = this.selectVariety2.filter(item => item.varietyNumber !== record.varietyNumber)
      }
    },
    varietyOnSelectAll2(selected, selectedRows, changeRows) {//选择/取消选择所有商品的回调
      if (selected) {//如果是选择所有商品的操作，就将所选择的商品添加进selectVariety
        this.selectVariety2 = [...this.selectVariety2, ...changeRows]
      } else {//如果是取消选择所有商品的操作，则从selectVariety中删除相应的商品
        for (let i of changeRows) {
          this.selectVariety2 = this.selectVariety2.filter(item => item.varietyNumber !== i.varietyNumber)
        }
      }
    },
    varietyAdd2() {// 第二个弹窗中的新增商品
      for (let item of this.selectVariety2) {
        item.preinfoid = item.id
        item.createUser = ''
        item.createTime = ''
        item.updateTime = ''
        item.updateUser = ''
        const dataSource = [...this.varietyDataSource2]
        let x = dataSource.filter(item2 => item2.id === item.id)
        if (x.length == 0) {
          this.varietyDataSource2.push(item)
        }
      }
      this.varietyVisible2 = !this.varietyVisible2
      this.getTotalPrice2()
    },

    varietyDelete2(id) {// 第一个弹窗中删除商品
      const dataSource = [...this.varietyDataSource2]
      this.varietyDataSource2 = dataSource.filter(item => item.id !== id)

      this.getTotalPrice2()
    },
    getTotalPrice(){
      // 计算出合计总价
      this.allTotalPrice = 0
      for (let item of this.varietyDataSource) {
        if (ifNumber1(item.totalprice) && ifNumber1(item.number)) {
          this.allTotalPrice += item.totalprice * 10 / 10
          this.allTotalPrice = (this.allTotalPrice).toFixed(2)
        } else {
          this.allTotalPrice = null
          return
        }
      }
    },
    getTotalPrice2(){
      // 计算出合计总价
      this.allTotalPrice2 = 0
      for (let item of this.varietyDataSource2) {
        if (ifNumber1(item.totalprice) && ifNumber1(item.number)) {
          this.allTotalPrice2 += item.totalprice * 10 / 10
          this.allTotalPrice2 = (this.allTotalPrice2).toFixed(2)
        } else {
          this.allTotalPrice2 = null
          return
        }
      }
    },
    flowerPreAddOrEdit() {// 确定新增或编辑销售单
      let allNumberFlag = true//是否所有的商品都有数量的标识
      if (this.flowerPre.finaSureUser) {
        this.addOrEditVisible = !this.addOrEditVisible
        return
      }
      if (this.flowerPre.period === '') {
        this.$message.error('请选择账期')
      } else if (this.flowerPre.channel === '') {
        this.$message.error('请选择渠道')
      } else if (this.accountnoShow && this.flowerPre.accountno === '') {
        this.$message.error('请选择账号')
      } else if (!this.flowerPre.isinvoice) {
        this.$message.error('请选择是否开票')
      }
      /*else if (!this.flowerPre.user) {
        this.$message.error('请填写客户')
      }*/
      else if (!this.flowerPre.address) {
        this.$message.error('请填写地址')
      }/* else if (!this.flowerPre.stockOutTime) {
        this.$message.error('请填写出库日期')
      }*/ else {
        if (this.varietyDataSource.length === 0) {
          this.$message.error('请至少添加一个商品')
          return
        }
        for (let item of this.varietyDataSource) {
          if (item.number === '' || item.number === null) {
            this.$message.error('请输入销售数量')
            allNumberFlag = false
            return
          }
          if (item.price === '' || item.price === null) {
            this.$message.error('请输入单价')
            allNumberFlag = false
            return
          }

          if (!ifInteger(item.number)) {
            this.$message.error('销售数量必须为正整数')
            return
          }
          if (!ifNumber(item.price)) {
            this.$message.error('单价必须为数字')
            return
          }
        }
        /*}*/
        if (allNumberFlag) {
          // 去掉varietyDataSource中每个对象（如果有）的uuid，此uuid是在前端生成的
          this.varietyDataSource.map(item => {
            delete item.uuid
          })

          this.flowerPre.flowerPreinfoList = this.varietyDataSource// 将商品列表封装近flowerPre中
          this.flowerPre.flowerPreinfoHsList = this.varietyDataSource2// 将商品列表封装近flowerPre中
          if (this.addOrEditFlag === 'add') {// 新增销售单的情况
            this.firstModalSaveLoading = true
            this.firstModalSpinning = true
            flowerPreAdd(this.flowerPre).then(res => {
              if (res.success) {
                this.queryFlowerPre()
                this.$message.success('新增销售成功')
                this.addOrEditVisible = false
              } else {
                this.$message.error(res.message)
              }
              this.firstModalSaveLoading = false
              this.firstModalSpinning = false
            })
          } else {
            this.firstModalSaveLoading = true
            this.firstModalSpinning = true
            flowerPreEdit(this.flowerPre).then(res => {// 编辑销售单的情况
              if (res.success) {
                this.queryFlowerPre()
                this.$message.success('编辑销售成功')
                this.addOrEditVisible = false
              } else {
                this.$message.error(res.message)
              }
              this.firstModalSaveLoading = false
              this.firstModalSpinning = false
            })
          }
          this.selectedRowKeys.length = 0//使新增或编辑后不显示批量删除的按钮
        }
      }
    },
    flowerPreDelete(id) {
      flowerPreDelete({ id: id }).then(res => {
        if (res.success) {
          this.queryFlowerPre()
          this.$message.success('删除成功')
        } else {
          this.$message.error(res.message)
        }
      })
    },
    flowerPreBatchDelete(selectedRowKeys) {
      if (selectedRowKeys.length > 0) {
        let ids = ''
        for (let item of selectedRowKeys) {
          ids = ids + item + ','
        }
        flowerPreDeleteBatch({ ids: ids }).then(res => {
          if (res.success) {
            this.queryFlowerPre()
            this.selectedRowKeys.length = 0
            this.$message.success('批量删除成功')
          } else {
            this.$message.error(res.message)
          }
        })
      }
    },
    autugetprice(record, number, totalprice) {
      if (number && totalprice) {
        if (number == 0 || number == '0') {
          record.number = null
          record.price = null
        } else {
          let price = (totalprice * 10 / 10) / (number * 10 / 10)
          record.price = parseFloat(price).toFixed(2)
        }
      }
      this.getTotalPrice()

    },
    //是否开票的单项
    isinvoiceChange(e) {
      this.flowerPre.isinvoice = e.target.value
    },
    //获取渠道
    getChannel() {
      getFlowerChannel().then(res => {
        if (res.success) {
          this.channelList = res.result.records
        } else {
          this.$message.error(res.message)
        }
      })
    },
    //渠道选择框的change
    channelChange(value, option) {
      this.accountnoList.length = 0
      this.flowerPre.accountno = ''
      this.varietyDataSource.length = 0//处理重新选择渠道后，要置空之前已选择的商品
      this.getAccountnoByMainId(option.key)
    },
    //根据渠道id获取账号
    getAccountnoByMainId(channelId) {
      let params = { id: channelId }
      getFlowerAccountByMainId(params).then(res => {
        if (res.success) {
          this.accountnoList = res.result
          if (this.accountnoList.length === 0) {
            this.accountnoShow = false
          } else {
            this.accountnoShow = true
          }
        } else {
          this.$message.error('未找到对应的账号')
        }
      })
    },
    // 日期选择框中不可选择的日期
    disabledDate(current) {
      return current < moment().subtract(1, 'day')//当前日期以前不可用
    },
    getPeriod() {
      period().then(res => {
        this.periodList = res
      })
    },
    //账期单选的change
    periodChange(e) {
      this.flowerPre.period = e.target.value
    },
    //设置账期（打开编辑弹窗时用）
    setPeriod() {
      period().then(res => {
        this.periodList = res
        if (this.periodList.length === 1) {//账期开关关闭时
          this.periodList.push(this.flowerPre.period)
          this.periodList = Array.from(new Set(this.periodList))//去重
          this.periodList.sort()//升序排序
        }
      })
    },
    //客户相关----start----
    customModalShow() {//打开客户选择弹窗
      /*设置下面这两行是为了处理再次打开客户选择弹窗时，
      还会在界面上保留上次选择客户而实际上没有选择任何客户的问题*/
      this.selectedRowKeys.length = 0
      this.selectionRows.length = 0

      this.customPagination = {// 客户表格的分页
        total: 0,
        current: 1,
        pageSize: 10,//每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],//每页中显示的数据
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      }
      this.queryCustomParams = {// 客户选择弹窗的查询
        name: '',
        phone: ''
      }
      this.customVisible = true
      this.queryFlowerCustom()
    },
    //获取客户列表
    queryFlowerCustom() {
      this.customLoading = true
      let params = {
        pageNo: this.customPagination.current,
        pageSize: this.customLoading.pageSize
      }
      params = { ...this.queryCustomParams, ...params }
      getFlowerCustom(params).then(res => {
        if (res.success) {
          this.customPagination.total = res.result.total
          this.customDataSource = res.result.records
        } else {
          this.$message.error(res.message)
        }
        this.customLoading = false
      })
    },
    customOnChange(selectedRowKeys, selectionRows) {//选择客户弹窗中选择客户时的回调
      this.selectedRowKeys = selectedRowKeys// 如果不加这两行的话无法多选
      this.selectionRows = selectionRows

      this.selectCustom = selectionRows[0]
    },
    selectCustomPaginationChange(pagination) {
      this.customPagination = pagination
      this.queryFlowerCustom()
    },
    customAdd() {// 客户选择中的确定选择客户
      if (JSON.stringify(this.selectCustom) !== '{}') {
        this.flowerPre.userid = this.selectCustom.id
        this.flowerPre.user = this.selectCustom.name
        this.flowerPre.phone = this.selectCustom.phone
        this.flowerPre.address = this.selectCustom.address
      }
      this.customVisible = false
    },
    searchCustom() {// 客户选择弹窗中的查询客户
      this.queryFlowerCustom()
    },
    //客户相关----end----

    handleExportXls() {
      let fileName = '销售确认单导出'
      let param = this.queryParams
      this.exportLoading = true

      if (this.selectedRowKeys && this.selectedRowKeys.length > 0) {
        param['selections'] = this.selectedRowKeys.join(',')
      }
      let urlss = this.url.exportXlsUrl
      downFile(urlss, param).then((data) => {
        if (!data) {
          this.$message.warning('文件下载失败')
          return
        }
        if (typeof window.navigator.msSaveBlob !== 'undefined') {
          window.navigator.msSaveBlob(new Blob([data], { type: 'application/vnd.ms-excel' }), fileName + '.xlsx')
          this.exportLoading = false
        } else {
          let url = window.URL.createObjectURL(new Blob([data], { type: 'application/vnd.ms-excel' }))
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName + '.xlsx')
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) //下载完成移除元素
          window.URL.revokeObjectURL(url) //释放掉blob对象
          this.exportLoading = false
        }
      })
    },

    // -----预出库单号  --start----
    // -----预出库单号  --start----
    preorderModalShow() {//打开客户选择弹窗

      /*设置下面这两行是为了处理再次打开客户选择弹窗时，
      还会在界面上保留上次选择客户而实际上没有选择任何客户的问题*/
      this.selectedRowKeys.length = 0
      this.selectionRows.length = 0


      let realname = store.getters.userInfo.realname
      let phone = store.getters.userInfo.phone
      let userName = store.getters.userInfo.username

      this.preorderPagination = {// 客户表格的分页
        total: 0,
        current: 1,
        pageSize: 10,//每页中显示10条数据
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],//每页中显示的数据
        showTotal: total => `共有 ${total} 条数据`  //分页中显示总的数据
      }
      this.querypreorderParams = {// 查询初始化
        orderNo: '',
        state: 0,
        createUser: userName
      }
      this.queryPreOrder()
      this.preorderVisible33 = true

    },
    //获取列表
    queryPreOrder() {
      this.customLoading = true
      let params = {
        pageNo: this.preorderPagination.current,
        pageSize: this.preorderPagination.pageSize
      }
      params = { ...this.querypreorderParams, ...params }
      getFlowerPreOutorder(params).then(res => {
        if (res.success) {
          this.preorderPagination.total = res.result.total
          this.preorderDataSource = res.result.records
        } else {
          this.$message.error(res.message)
        }
        this.customLoading = false
      })
    },
    preorderOnChange(selectedRowKeys, selectionRows) {//选择客户弹窗中选择客户时的回调
      this.selectedRowKeys = selectedRowKeys// 如果不加这两行的话无法多选
      this.selectionRows = selectionRows
      this.selectpreOrder = selectionRows[0]
    },
    selectPreOrderPaginationChange(pagination) {
      this.preorderPagination = pagination
      this.queryPreOrder()
    },
    PreOrderAdd() { // 确定
      if (JSON.stringify(this.selectpreOrder) !== '{}') {
        this.flowerPre.outorderPreNo = this.selectpreOrder.orderNo
        this.flowerPre.channel = this.selectpreOrder.channel
        this.flowerPre.accountno = this.selectpreOrder.accountno
        this.flowerPre.address = this.selectpreOrder.address

        if (!this.flowerPre.outorderPreNo) {
          this.$message.error('选择数据有误，请重试')
          return
        }
        this.preOrderInfoList = []
        this.varietyDataSource = []
        //根据与出库单，带出预出库的子表数据库
        this.queryPreOrderInfolistByNo(this.flowerPre.outorderPreNo, false)
      }
      this.preorderVisible33 = false
    },
    searchPreOrder() {//  查询
      this.queryPreOrder()
    },
    queryPreOrderInfolistByNo(orderNo, isEdit) {
      this.preOrderInfoList = []
      getPreOrderInfolistByNo({ 'orderNo': orderNo }).then((res) => {
        if (res.success) {
          this.preOrderInfoList = res.result//缓存预出库单所有子表数据。
          if (!isEdit) {
            if (this.preOrderInfoList.length == 0) {
              this.$message.error('选择数据有误，请重试')
              return
            }
            let that = this
            this.preOrderInfoList.map(item => {
              let newItem = {}
              newItem.classes = item.classes
              newItem.cost = item.cost
              newItem.flowerPoleLength = item.flowerPoleLength
              newItem.number = item.number
              newItem.preinfoid = item.id
              newItem.packingSpecifications = item.packingSpecifications
              newItem.price = item.price
              newItem.sourceBase = item.sourceBase
              newItem.sourceGreenhouse = item.sourceGreenhouse
              newItem.storehouse = item.storehouse
              newItem.totalprice = item.totalprice
              newItem.variety = item.variety
              newItem.varietyCode = item.varietyCode
              that.varietyDataSource.push(newItem)//销售子表数据
            })
          }
        } else {
          this.$message.error(res.message)
        }
      })
    },
    // -----预出库单号  --end----


    sealSure(record){
      this.firstModalSaveLoading=true
      pipSureOut({ 'id': record.id }).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.addOrEditVisible = !this.addOrEditVisible
          this.queryFlowerPre()
        } else {
          this.$message.error(res.message)
        }
        this.firstModalSaveLoading=false
      })
    },
    sealSureBack(record){
      this.firstModalSaveLoading=true
      pipSureOutBack({ 'id': record.id }).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.addOrEditVisible = !this.addOrEditVisible
          this.queryFlowerPre()
        } else {
          this.$message.error(res.message)
        }
        this.firstModalSaveLoading=false
      })
    },

  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
.ant-col {
  margin-top: 3px;
  height: 40px;
}
</style>